part of '../../flutter_ns_ble.dart';

class B1SyncDataReader {
  final String sourceFilePath;
  final String targetFilePath;

  B1SyncDataReader({
    required this.sourceFilePath,
    required this.targetFilePath,
  });

  Stream<double> process({EcgFile? ecgFile}) async* {
    var file = File(sourceFilePath);
    final fileLength = await file.length();
    final writer = File(targetFilePath).openSync(mode: FileMode.write);

    final frameSize = (Platform.isAndroid ? 244 : 184);

    final readStream = file.openRead();
    var lastIndex = -1;
    int progress = 0;
    var data = List<int>.empty(growable: true);

    await for (final chunk in readStream) {
      data += chunk;
      var chunks = data.chunked(frameSize);
      for (var buffer in chunks) {
        if (buffer.length == frameSize) {
          BlePacket packet = BlePacket.fromBytes(buffer);
          var index = Uint8List.fromList([
            ...packet.data.sublist(0, 3),
            0,
          ]).buffer.asByteData().getInt32(0, Endian.little);
          print("写入数据: $index");
          if (progress > 0) {
            await writer.writeString(",");
          }
          if (lastIndex == -1) {
            lastIndex = index;
          } else if (index != lastIndex + 1) {
            print("missing packet:${lastIndex},index:$index,${buffer.toHex(separator: "_")}");
            throw Exception("missing packet");
          } else {
            var data = packet.data.sublist(4);
            var byteData = Uint8List.fromList(data).buffer.asByteData();
            var points = List<int>.empty(growable: true);
            for (var i = 0; i < byteData.lengthInBytes / 2; i++) {
              var num = byteData.getInt16(i * 2, Endian.little);
              points.add(num);
              await writer.writeString("${num}");
            }
            await ecgFile?.writeFrom(points.map((e) => e.toDouble()).toList());
          }
          progress += buffer.length;
          yield progress / fileLength;
          lastIndex = index;
        }else{
          data = buffer;
        }
      }
    }

    await writer.flush();
    await writer.close();
  }
}
